import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {SettingsService} from '../settings/settings.service';
declare var $: any;
const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded'})
};

@Injectable()
export class AuthService {
  private baseUrl: String;
  constructor(private http: HttpClient, private settings: SettingsService) {
    this.baseUrl = this.settings.getBaseServerUrl();
  }

  chickToken (accessToken: String): boolean {
    const url = '/uaa/oauth/check_token';
    const res = this.http.get(this.baseUrl + url + '?token=' + accessToken);
    res.subscribe(r => {
      console.log(res);
    })

    return true;
  }
  login (user: {username?: String, password?: String}): Promise<void> {
    const url = '/uaa/oauth/token';
    const body = {
      'grant_type': 'password',
      'scope': 'app',
      'password': user.password,
      'username': user.username
    };
    return this.http.post(this.baseUrl + url, $.param(body), httpOptions)
      .toPromise().then(data => {
        if (data) {
          localStorage.setItem('access_token', data['access_token']);
          localStorage.setItem('refresh_token', data['refresh_token']);
        }
      });
  }
}
